package com.village.friend.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.village.friend.constant.PayStatus;
import com.village.friend.constant.PolicyType;
import com.village.friend.dto.request.BasePageDto;
import com.village.friend.dto.request.BaseTimeDto;
import com.village.friend.dto.request.GetUserDto;
import com.village.friend.dto.request.UpdateUserDto;
import com.village.friend.dto.response.BaseResponse;
import com.village.friend.dto.response.UserResDto;
import com.village.friend.entity.*;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 参数转换工具
 */
public class ParamUtils {


    /**
     * list 转化为 json字符串
     *
     * @param list
     * @return
     */
    public static String toJSONString(List list) {
        if (list == null || list.size() == 0) {
            return null;
        }
        return JSON.toJSONString(list);
    }

    /**
     * list 转化为 字符串
     *
     * @param list
     * @return
     */
    public static String toString(List list) {
        if (list == null || list.size() == 0) {
            return null;
        }
        return StringUtils.join(list, ",");
    }

    /**
     * json字符串 转化为 list
     *
     * @param str
     * @return
     */
    public static List jsonStrToList(String str) {
        return JSONObject.parseObject(str, ArrayList.class);
    }

    /**
     * list 转化为 字符串T
     *
     * @param str
     * @return
     */
    public static List strToList(String str) {
        if (str == null) {
            return new ArrayList();
        }
        String[] split = str.split(",");
        List<String> list = new ArrayList<>();
        Collections.addAll(list, split);
        return list;
    }

    /**
     * 数据库 user 转化为 userResDto
     *
     * @param user
     * @return
     */
    public static UserResDto userToUserResDto(User user) {
        UserResDto data = new UserResDto();
        data.setUsername(user.getUsername());
        data.setAvatarurl(user.getAvatarurl());
        data.setNickname(user.getNickname());
        data.setAge(user.getAge());
        data.setWeight(user.getWeight());
        data.setHeight(user.getHeight());
        data.setPhotos(ParamUtils.jsonStrToList(user.getPhotos()));
        data.setIsHide(user.getIsHide());
        data.setVipLevel(user.getVipLevel());
        data.setVipLeft(user.getVipLeft());
        data.setOnline(user.getOnline());
        data.setCity(user.getCity());
        data.setProfession(user.getProfession());
        data.setSalaryYear(user.getSalaryYear());
        data.setSelfDesc(user.getSelfDesc());
        data.setWeChatAccount(user.getWechatAccount());
        data.setFlags(ParamUtils.strToList(user.getFlags()));
        data.setInviteCode(user.getInviteCode());
        data.setToken(user.getToken());
        return data;

    }
    public static User update2User(UpdateUserDto dto) {
        User user = new User();
        user.setNickname(dto.getNickname());
        user.setAvatarurl(dto.getAvatarurl());
        if(StringUtils.isNotBlank(dto.getBirth())) {
            user.setBirth(LocalDate.parse(dto.getBirth()));
        }
        user.setHeight(dto.getHeight());
        user.setWeight(dto.getWeight());
        if(dto.getPhotos() != null) {
            user.setPhotos(ParamUtils.toJSONString(dto.getPhotos()));
        }
        user.setIsHide(dto.getIsHide());
        user.setIsLogout(dto.getIsLogout());
        if(dto.getFlags() != null) {
            user.setFlags(ParamUtils.toJSONString(dto.getFlags()));
        }
        user.setCity(dto.getCity());
        user.setSelfDesc(dto.getSelfDesc());
        user.setProfession(dto.getProfession());
        user.setSalaryYear(dto.getSalaryYear());
        user.setWechatAccount(dto.getWeChatAccount());

        return user;

    }


    /**
     * 生成订单信息
     * @param user 用户信息
     * @param channelName 支付渠道
     * @param id    订单id
     * @param business 交易类型
     * @param orderPrice 订单金额
     * @param productName 产品名称
     * @param payStatus 订单状态
     * @return
     */
    public static AppPaymentOrder genOrder(User user, String channelName, String id, PolicyType business,
                                           BigDecimal orderPrice, String productName, PayStatus payStatus
    ){
        AppPaymentOrder tradePaymentOrder = new AppPaymentOrder();
        tradePaymentOrder.setId(id);

//        `user_id` varchar(32) DEFAULT NULL COMMENT '用户ID',
//        `full_name` varchar(128) DEFAULT NULL COMMENT '用户名称',
        if (user == null) {
            throw new RuntimeException("用户信息不能为空");
        }
        tradePaymentOrder.setUserId(user.getUsername());
        tradePaymentOrder.setFullName(user.getNickname());
//        `product_name` varchar(128) DEFAULT NULL COMMENT '商品名称',
        // 商品名称
        tradePaymentOrder.setProductName(productName);
//        `order_amount` decimal(20,6) DEFAULT NULL COMMENT '订单金额',
//        `profit_amount` decimal(20,6) DEFAULT NULL COMMENT '分润金额',
        //订单金额不为空 或者 > 0
        if (orderPrice == null || orderPrice.doubleValue() <= 0) {
            throw new RuntimeException("订单金额错误");
        }
        tradePaymentOrder.setOrderAmount(orderPrice);// 订单总金额
        //TODO 分润金额
//        tradePaymentOrder.setProfitAmount(orderPrice);// 分润金额

//        `pay_status` varchar(64) DEFAULT NULL COMMENT '支付状态 见支付状态枚举',
        tradePaymentOrder.setPayStatus(payStatus.getValue());

//        `order_period` smallint DEFAULT NULL COMMENT '订单有效期',
//        `expire_time` datetime DEFAULT NULL COMMENT '到期时间',
        tradePaymentOrder.setOrderPeriod(120);//有效期120分钟
        tradePaymentOrder.setExpireTime(LocalDateTime.now().plusHours(2));

//        `pay_way_name` varchar(64) DEFAULT NULL COMMENT '支付渠道名称',
        tradePaymentOrder.setPayWayName(channelName);


//        `split_flag` varchar(1) DEFAULT NULL COMMENT '是否分账  0：否 1：是 ',
//        `recon_flag` varchar(1) DEFAULT NULL COMMENT '是否对账  0：否 1：是 ',
        tradePaymentOrder.setSplitFlag("0");
        tradePaymentOrder.setReconFlag("0");


//        `pay_type_name` varchar(64) DEFAULT NULL COMMENT '支付类型名称',
//        `pay_type_no` varchar(32) DEFAULT NULL COMMENT '支付类型编码',
        tradePaymentOrder.setPayTypeNo(business.getType());
        tradePaymentOrder.setPayTypeName(business.getName());


//        `failed_reason` varchar(512) DEFAULT NULL COMMENT '失败原因',
//        `remark` varchar(512) DEFAULT NULL COMMENT '备注',
//        `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
//        `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
//        tradePaymentOrder.setRemark();



        return tradePaymentOrder;
    }

    /**
     * 把上级的对应关系转换成lv: username 的map格式
     * @param parentUsers
     * @return
     */
    public static Map<Integer,String> parentMapping2Map(List<AppUserMapping> parentUsers){
        Map<Integer,String> resultMap = new HashMap<>();
        if(parentUsers != null && parentUsers.size() > 0){
            for (AppUserMapping mapping : parentUsers) {
                resultMap.put(mapping.getLv(), mapping.getParentId());
            }
        }
        return resultMap;
    }

    /**
     * 把user list转换成map格式
     * @param users
     * @return
     */
    public static Map<String,User> user2Map(List<User> users){
        Map<String,User> resultMap = new HashMap<>();
        if(users != null && users.size() > 0){
            for (User user : users) {
                resultMap.put(user.getUsername(), user);
            }
        }
        return resultMap;
    }

    /**
     * 检查分润比例配置是否有效
     * @param profitList
     * @return
     */
    public static boolean checkProfit(List<ColValueBean> profitList){
        int profitValue = 0;
        for (ColValueBean bean :
                profitList) {
            if(bean.getValue() < 0){
                return false;
            }
            profitValue += bean.getValue();
        }
        return 100 >= profitValue;
    }

    public static void fullTime(BaseTimeDto param, QueryWrapper qw){

        if(StringUtils.isNotEmpty(param.getStartTime())){
            qw.ge("create_time",param.getStartTime());
        }
        if(StringUtils.isNotEmpty(param.getEndTime())){
            qw.le("create_time",param.getEndTime());
        }
    }

    public static void checkParam(Object param){
        if(param == null){
            throw new RuntimeException("参数错误");
        }
    }
}
